package com.jin.concurrent.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author JinLiu
 */
@Slf4j
public class SemaphoreExample2 {

    private final static int threadTotal = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < threadTotal; i++) {
            final int num = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire(5);
                    test(num);
                    semaphore.release(5);
                } catch (InterruptedException e) {
                    log.error("{}", e);
                }
            });
        }

        log.info("finish");
        executorService.shutdown();
    }

    private static void test(int num) throws InterruptedException {
        Thread.sleep(500);
        log.info("test: {}", num);
        Thread.sleep(500);
    }

}
